import { createLoginPasswordRepository } from './repository.login-password';
import { LoginPassword, $LoginPassword, UserId } from './model';
import { checkEncrypted, encrypt } from './utils'

const repository = createLoginPasswordRepository();

export async function findByUserId(userId: UserId): Promise<$LoginPassword> {
  return await repository.selectByUserId(userId);
}

export async function check(userId: UserId, realPassword: string): Promise<boolean> {
  const $persistedLp = await repository.selectByUserId(userId);
  if (!$persistedLp) {
    return false;
  }
  return checkEncrypted(realPassword, $persistedLp.encryptedPassword);
}

export async function save(userId: UserId, realPassword: string): Promise<void> {
  await repository.persist({ userId, encryptedPassword: encrypt(realPassword)});
}
